// import { setStore, getStore } from '@/util/store'
import { Message } from "element-ui";
import ActionTypes from "@/const/action";
import filterSaveData from "@/util/filterSaveData";
import { getStore } from "@/util/store";
import {
  SyncGetTableData,
  PromiseSaveDetailData,
  PromiseDeleteRow,
  SyncGetDetailData,
} from "@/api/table";

export default {
  namespaced: true,
  state: {
    tableData: [],
    pageOption: {
      total: 0, //总页数
      currentPage: 1, //当前页数
      pageSize: 10, //每页显示多少条
    },
    filterData: {},
    currentData: {}, // 当前详情页数据
    routerFormDetail: false,
    orderUnlessCount: 0,
    withdrawCommission: 0,
  },
  mutations: {
    SET_PAGE_OPTION(state, option) {
      state.pageOption = Object.assign({}, state.pageOption, option);
    },
    UPDATE_TABLE_DATA(state, data) {
      state.tableData = data;
    },
    SET_CURRENT_DATA(state, data) {
      state.currentData = data;
    },
    SET_ROUTER_FORM(state, payload) {
      state.routerFormDetail = payload;
    },
    SET_FILTER_DATA(state, data) {
      state.filterData = data;
    },
    SET_ORDER_UNLESS(state, count) {
      state.orderUnlessCount = count;
    },
    SET_WITHDRAW_COMMISSION(state, num) {
      state.withdrawCommission = num;
    },
  },
  actions: {
    CreateTableData({ commit, dispatch }, action) {
      commit("SET_PAGE_OPTION", {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      });
      commit("SET_FILTER_DATA", {});
      commit("SET_CURRENT_DATA", {});
      commit("UPDATE_TABLE_DATA", []);
      dispatch("GetTableData", action);
    },
    async GetTableData({ state, commit, dispatch }, action) {
      await dispatch("dic/getRoleDic", null, {
        root: true,
      });
      await dispatch("dic/getCityDic", null, {
        root: true,
      });
      const { currentPage, pageSize } = state.pageOption;
      const filterData = checkPageFilterData(action, { ...state.filterData });
      const { data, error } = await SyncGetTableData(action, {
        pageIndex: currentPage,
        pageSize: pageSize,
        ...filterData,
      });
      if (data) {
        if (action === ActionTypes.ORDER_MANAGE) {
          commit("UPDATE_TABLE_DATA", data.bussData.pageData.bussData);
          commit("SET_PAGE_OPTION", {
            total: data.bussData.pageData.count,
          });
          commit("SET_ORDER_UNLESS", data.bussData.count);
          return;
        }
        if (action === ActionTypes.WITHDRAW_MANAGE) {
          commit("UPDATE_TABLE_DATA", data.bussData.page.list);
          commit("SET_PAGE_OPTION", {
            total: data.bussData.page.total,
          });
          commit("SET_WITHDRAW_COMMISSION", data.bussData.commission);
          return;
        }
        commit("UPDATE_TABLE_DATA", data.bussData);
        commit("SET_PAGE_OPTION", {
          total: data.count,
        });
        return;
      }
      if (error) {
        Message({
          type: "error",
          message: error.message || String(error),
        });
      }
    },
    async GetDetailData({ commit }, { action, id = "" }) {
      const { data, error } = await SyncGetDetailData(action, id);
      if (error) {
        Message({
          type: "error",
          message: error.message || String(error),
        });
        return;
      }
      commit("SET_CURRENT_DATA", data.bussData);
    },
    saveDetailData(_, { action, formData }) {
      console.log(action, formData);
      let data = {
        ...formData,
      };
      if (action === ActionTypes.GOODS_MANAGE) {
        data = goodsFormatData(data);
      }
      if (action === ActionTypes.HOMEPAGE_POPUP) {
        data = popupFormatData(data);
      }
      if (action === ActionTypes.MERCHANT_LIST) {
        data = merchantFormatData(data);
      }
      if (action === ActionTypes.ROLE_MANAGE) {
        data = roleFormatData(data);
      }
      if (action === ActionTypes.ACCOUNT_AUTH) {
        data = accountFormatData(data);
      }
      if (action === ActionTypes.GOODS_CATEGORY_FIRST) {
        data = firstCatFormatData(data);
      }
      if (action === ActionTypes.REPAIR_QUESTION) {
        data.isPutAway = true;
      }
      if (action === ActionTypes.PERSONNEL_MANAGE) {
        data = personnelFormatData(data);
      }
      data = filterSaveData(data, action);
      return PromiseSaveDetailData(action, data);
    },
    PromiseDeleteRow({ dispatch }, { action, id, row }) {
      return new Promise((resolve, reject) => {
        let _id = id;
        if (action === ActionTypes.ACCOUNT_AUTH) {
          _id = row.userId;
        }
        PromiseDeleteRow(action, _id)
          .then(() => {
            dispatch("GetTableData", action);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

/**
 *  商品管理格式化data
 **/
function goodsFormatData(data) {
  function renameList({ id, name, type }) {
    return {
      relevanceId: id,
      relevanceName: name,
      relevanceType: type,
    };
  }

  let copyData = {
    ...data,
  }; // copy 一份data，对原数据不造成影响
  let list = copyData["${cityDTO}"]
    .map(renameList)
    .concat(copyData["${exhibitionDTO}"].map(renameList));

  if (!copyData.categorySonId) {
    delete copyData["categorySonId"];
  }

  if (copyData.isPutAway === undefined) {
    copyData.isPutAway = true;
  }

  delete copyData["${cityDTO}"];
  delete copyData["${exhibitionDTO}"];
  delete copyData["cityDTO"];
  delete copyData["exhibitionDTO"];

  copyData.list = list;
  copyData.price = Number(copyData.price);

  return copyData;
}

/**
 *  首页弹窗格式化data
 **/
function popupFormatData(data) {
  const copyData = {
    ...data,
  };
  if (copyData.popupType === "COUPON") {
    delete copyData.body;
  }
  if (copyData.popupType === "NOTICE") {
    delete copyData.discounts;
    delete copyData.fullMoney;
    delete copyData.startTime;
    delete copyData.endTime;
  }
  return copyData;
}

function merchantFormatData(data) {
  const copyData = {
    ...data,
  };
  copyData.list = [...data["${firstList}"], ...data["${childList}"]].map(
    (opt) => {
      return {
        categoryId: opt.id,
        categoryType: opt.type,
      };
    }
  );
  if (copyData["${password}"]) {
    copyData.password = copyData["${password}"];
    delete copyData["${password}"];
  } else {
    delete copyData["${password}"];
    delete copyData["password"];
  }

  delete copyData["firstList"];
  delete copyData["childList"];
  delete copyData["${firstList}"];
  delete copyData["${childList}"];
  return copyData;
}

function roleFormatData(data) {
  const copyData = {};
  copyData["permissionIds[]"] = data.permissionIds.map((option) => option.id);
  copyData.roleName = data.roleName;
  copyData.roleDescribe = data.roleDescribe;
  if (data.id) {
    copyData.id = data.id;
  }
  delete copyData.permissionIds;
  return copyData;
}

function accountFormatData(data) {
  const copyData = {
    ...data,
  };
  if (data.provinceCode === 0) {
    delete copyData.provinceCode;
  }
  copyData.mobile = String(data.mobile);
  copyData.roleId = data["${appRoleId}1"];
  copyData.userName = data.mobile;
  return copyData;
}

function firstCatFormatData(data) {
  const copyData = {
    ...data,
  };
  if (!copyData.isIndexShow) {
    delete copyData.indexSort;
  }
  return copyData;
}

function personnelFormatData(data) {
  const copyData = {
    ...data,
  };
  // 如果没有确认密码的值，不传mi ma
  if (
    !copyData.affirmPassword ||
    copyData.password !== copyData.affirmPassword
  ) {
    delete copyData.password;
    delete copyData.affirmPassword;
  }
  return copyData;
}

// 检查filterData
function checkPageFilterData(action, data) {
  const copyData = { ...data };
  const userInfo = getStore({ name: "userInfo" }) || {};
  // 如果筛选字段里有结束时间，加一天
  if (copyData.startTime && copyData.endTime) {
    let newEndTime =
      new Date(copyData.endTime).getTime() + (24 * 60 * 60 - 1) * 1000;
    copyData.endTime = new Date(newEndTime).toISOString();
  } else if (copyData.startTime) {
    copyData.endTime = new Date().toISOString();
  } else if (copyData.endTime) {
    copyData.startTime = new Date("1970-01-01 00:00:00").toISOString();
  }
  if (
    action === ActionTypes.ORDER_MANAGE ||
    action === ActionTypes.MAINTAIN_ORDER
  ) {
    copyData.provinceCode = userInfo.provinceCode;
    copyData.cityCode = userInfo.cityCode;
  }
  return copyData;
}
